package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Scanner;

public class SendNewsToAllService implements Runnable{
    @Override
    public void run() {
        while(true)
        {
            System.out.print("请输入服务器要推送的新闻/消息[输入exit表示退出推送服务]:");
            String news= Utility.readString(100);
            if("exit".equals(news))
            {
                break;
            }
            Message message=new Message();
            message.setSender("服务器");
            message.setContent( news);
            message.setMesType(MessageType.MESSAGE_TO_ALL);
            message.setSendTime(new java.util.Date().toString());
            System.out.println("服务器推送新闻/消息给所有人");
            HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();
            for(String userId:hm.keySet())
            {
                ServerConnectClientThread serverConnectClientThread = hm.get(userId);
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
